package com.geeka.d12.work.chatroom;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;

public class SocketTask implements Runnable {
    private String s;
    private Socket socket;
    private ArrayList<Socket> sockets;

    public SocketTask(ArrayList<Socket> sockets, Socket socket) {
        this.socket = socket;
        this.sockets = sockets;
    }

    @Override
    public void run() {
        System.out.println("创建了连接客户端的socket");


        BufferedReader br = null;

        try {
            InputStream ips = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(ips));

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        s = null;
        System.out.println("listen to client");
        while (true) {
            try {
                if ((s = br.readLine()) != null) {
                    s = socket.getRemoteSocketAddress().toString() + " 说: " + s;
                    System.out.println(s);
                    sockets.forEach(socket1 -> {
                        if (socket1!=socket){
                            try {
                                OutputStream ops = socket1.getOutputStream();
                                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ops));

//                                PrintStream ps = new PrintStream(ops);
//                                ps.println(s);
//                                ps.flush();
                                bw.write(s);
                                bw.newLine();
                                bw.flush();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    });

                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}

